package com.bstek.uflo.console.controller;

import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.context.ApplicationContext;
import org.springframework.web.servlet.ModelAndView;

import com.bstek.uflo.process.node.reminder.CalendarInfo;
import com.bstek.uflo.process.node.reminder.CalendarProvider;

/**
 * @author Jacky.gao
 * @since 2013年9月10日
 */
public class CalendarProviderController extends AbstractController {
	@Override
	protected ModelAndView doHandleRequest(HttpServletRequest request,HttpServletResponse response) throws Exception {
		preCheck();
		ObjectMapper mapper=new ObjectMapper();
		response.setContentType("text/json");  
		response.setCharacterEncoding("UTF-8");  
		OutputStream out=response.getOutputStream();
		try{
			List<CalendarInfo> providers=getCalendarInfos();
			mapper.writeValue(out, providers);
		}finally{
			out.flush();
			out.close();
		}
		return null;
	}

	public List<CalendarInfo> getCalendarInfos(){
		List<CalendarInfo> providers=new ArrayList<CalendarInfo>();
		Map<String,CalendarProvider> providerMap=getApplicationContext().getBeansOfType(CalendarProvider.class);
		ApplicationContext context=getApplicationContext().getParent();
		if(context!=null){
			providerMap.putAll(context.getBeansOfType(CalendarProvider.class));
		}
		for(String id:providerMap.keySet()){
			List<CalendarInfo> list=providerMap.get(id).getCalendarInfos();
			if(list!=null && list.size()>0){
				providers.addAll(list);				
			}
		}
		return providers;
	}
}
